package com.learning.thread.juc.collection;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * ClassName: CountPoolExecutor
 * Description: 自定义的 ThreadPoolExecutor ，扩展了其 afterExecute方法进行统计
 * Date: 2018/7/6 11:15 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class CountPoolExecutor extends ThreadPoolExecutor {

    /**
     * 统计执行次数
     */
    AtomicInteger count = new AtomicInteger(0);

    private long startTime;
    private String functionName;
    private int taskCount;

    public CountPoolExecutor(long startTime, String functionName, int taskCount,
                             int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
        this.startTime = startTime;
        this.functionName = functionName;
        this.taskCount = taskCount;

    }


    @Override
    protected void afterExecute(Runnable r, Throwable t) {

        // 每次执行玩一个任务就加 1
        int i = count.addAndGet(1);

        if (i == taskCount) {
            System.out.println(functionName + " speed time: " + (System.currentTimeMillis() - startTime));
        }
    }
}
